import time

import selenium.webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from config import *
import re
class WebUtil():
    def __init__(self):
        options = selenium.webdriver.ChromeOptions()
        #忽略日志
        options.add_experimental_option(
            'excludeSwitches', ['enable-logging'])
        self.driver = selenium.webdriver.Chrome('E:/chromedirver/chromedriver-win64/chromedriver-win64/chromedriver.exe', options=options)
        #设置隐性等待时间
        self.driver.implicitly_wait(10)

    def login(self, name, pwd):
        self.driver.get(LOGIN_URL)
        if name:
            self.driver.find_element(By.ID, 'username').send_keys(name)
        if pwd:
            self.driver.find_element(By.ID, 'password').send_keys(pwd)
        self.driver.find_element(By.ID, 'loginBtn').click()

    def add_device_data(self, name, deid, desc):
        select = Select(self.driver.find_element(By.CSS_SELECTOR, '#device-type'))
        # 选中对应设备名称
        select.select_by_visible_text(name)
        # 添加设备编号
        ele = self.driver.find_element(By.ID, 'device-model')
        ele.clear()
        ele.send_keys(deid)
        # 添加设备描述
        ele = self.driver.find_element(By.ID, 'device-model-desc')
        ele.clear()
        ele.send_keys(desc)
        # click agree
        self.driver.find_element(By.CSS_SELECTOR, '.add-one-submit-btn-div>span').click()

    def get_first_data(self):
        time.sleep(0.5)
        self.driver.implicitly_wait(0)
        lst = self.driver.find_elements(By.CLASS_NAME, 'field-value')
        self.driver.implicitly_wait(10)
        result = []
        # 每3个数据为一组
        for i in range(len(lst)):
            if (i+1) % 3 == 0:
                result.append([
                    lst[i-2].text, lst[i-1].text, lst[i].text
                ])
        return result
    def dele_first_data(self):
        time.sleep(0.5)
        # 确定有数据显示
        self.driver.implicitly_wait(0)
        dele = self.driver.find_elements(By.CSS_SELECTOR, '.result-list-item-btn-bar > span:nth-child(1)')
        self.driver.implicitly_wait(10)
        if dele:
            dele[0].click()
        self.driver.switch_to.alert.accept()

    def change_first_data(self, deid, desc):
        self.driver.implicitly_wait(0)
        change = self.driver.find_elements(By.CSS_SELECTOR, '.result-list-item-btn-bar > span:nth-child(2)')
        self.driver.implicitly_wait(10)
        if change:
            change[0].click()
            ele = self.driver.find_element(By.CSS_SELECTOR, '.edit-one-form > div:nth-child(2) > input')
            ele.clear()
            ele.send_keys(deid)

            ele = self.driver.find_element(By.CSS_SELECTOR, '.edit-one-form > div:nth-child(3) > input')
            ele.clear()
            ele.send_keys(desc)

            self.driver.find_element(By.CSS_SELECTOR, '.result-list-item-btn-bar > span:nth-child(1)').click()

    def add_service_data(self,name: str,
        type: str,
        desc: str,
        min_cost: str = '',
        expect_cost: str = '',
        unit: [int, int] = None,
        rate: dict = None):

        # write name
        ele = self.driver.find_element(By.CSS_SELECTOR, '.add-one-area > div > div:nth-child(1) > input')
        ele.clear()
        ele.send_keys(name)

        # select type
        select = Select(self.driver.find_element(By.ID, 'rule_type_id'))
        select.select_by_visible_text(type)

        if min_cost:
            # min_cost
            ele = self.driver.find_element(By.XPATH,
                                           '//*/span[text()="最小消费"]/following-sibling::input')
            ele.clear()
            ele.send_keys(min_cost)

            # expect_cost
            ele = self.driver.find_element(By.XPATH,
                                           '//*/span[text()="预估消费"]/following-sibling::input')
            ele.clear()
            ele.send_keys(expect_cost)

        # unit
        if unit:
            father = self.driver.find_element(By.CLASS_NAME, 'fee-rate')
            ipt = father.find_elements(By.XPATH, './input')
            for i in range(2):
                ipt[i].clear()
                ipt[i].send_keys(unit[i])

        # add rate
        if rate:
            select.select_by_visible_text('预付费-下发业务量')
            select.select_by_visible_text(type)
            btn = self.driver.find_element(By.CSS_SELECTOR, '.fee-rate-list>div>button')
            for _ in range(len(rate)-1):
                btn.click()
            ipts = self.driver.find_elements(By.CSS_SELECTOR, '.fee-rate')
            for i, j in enumerate(rate):
                ipt = ipts[i].find_elements(By.XPATH, './input')
                ipt[0].send_keys(j); ipt[1].send_keys(rate[j][0]); ipt[2].send_keys(rate[j][1])






        # describe
        ele = self.driver.find_element(By.XPATH,
                                       '//*/span[text()="规则描述"]/following-sibling::input')
        ele.clear()
        ele.send_keys(desc)

        # add_btn
        self.driver.find_element(By.CSS_SELECTOR, '.add-one-submit-btn-div>span').click()

    def get_first_service_data(self, dic) -> dict:
        father = self.driver.find_element(By.CSS_SELECTOR, '.result-list > div:nth-child(1)')
        # dic = {
        #     '规则名称': name,
        #     '规则类型': type,
        #     '规则描述': desc,
        #     '规则内容': [min_cost, expect_cost, unit]
        #     # 'expect_cost':
        #     # "rate": rate
        # }
        dic_result = {}
        for i in father.find_elements(By.CLASS_NAME, 'field'):
            ele = i.find_element(By.CLASS_NAME, 'field-name').text
            if ele != '规则内容':
                dic_result[ele] = i.find_element(
                    By.CLASS_NAME, 'field-value').text
            else:
                self.driver.implicitly_wait(1)
                if dic.get('规则内容', 0):
                    lst = i.find_elements(By.XPATH, './/span[@class="field-value"]')
                    dic_result[ele] = [lst[1].text, lst[2].text]
                    if i.find_elements(By.XPATH, './/span[@class="sub-field-name" and text()="费率"]'):
                        add = i.find_elements(By.XPATH, './/span[@class="sub-field-name" and text()="费率"]/../div//span')
                        dic_result[ele].append(
                            [add[0].text.split('：')[-1].strip(),
                             add[1].text.split('：')[-1]]
                        )

                else:
                    eles = self.driver.find_elements(By.XPATH, '//span[@class = "sub-field-name"]/following-sibling::div/div/span')
                    rate = {}
                    f = lambda x: x.text.split('：')[-1].strip()
                    for i in range(len(eles)):
                        if (i+1) % 3 == 0:
                            rate[f(eles[i-2])] = [f(eles[i-1]), f(eles[i])]
                    dic_result['rate'] = rate

                self.driver.implicitly_wait(10)
        return dic_result





web_util = WebUtil()
